<template>
    <div class="mobile-content">
      <Sticky>
        <Search
            v-model.trim="searchForm.keyword"
            :show-action="false"
            placeholder="请输入搜索关键词"
            @search="onRefresh"
            @cancel="list= [];allList= [];"
        />
  
        <DropdownMenu>
          <DropdownItem v-model="filter.indexer" :options="indexerOptions" @change="onFilter"/>
          <!-- <DropdownItem v-model="filter.trackerType" :options="trackerTypeOptions" /> -->
          <DropdownItem title="筛选" ref="dItem">
            <Cell center title="Free">
              <template #right-icon>
                <Switch v-model="filter.onlyFree"/>
              </template>
            </Cell>
            <div style="padding: 5px 16px;">
              <Button type="primary" block round @click="()=>{dItem.toggle();onFilter()}">
                确 认
              </Button>
            </div>
          </DropdownItem>
        </DropdownMenu>
      </Sticky>
      <PullRefresh v-model="refreshing" @refresh="onRefresh">
        <List v-model:loading="loading" :finished="finished" finished-text="没有更多了" v-model:error="error"
          :error-text="errorText" :immediate-check="false" @load="onLoad">
          <Cell v-for="(item, index) in list" :key="item.id" clickable @click="opShowFunc(item)">
            <template #title>
              <div class="row-title">
                <span>{{  index + 1  }}.</span>
                <Tag plain v-if="item.isAdd" type="success">已添加</Tag>
                <span>{{  item.Title  }}&nbsp;</span>
                <Space>
                  <Tag  mark plain type="primary">{{  CommonUtil.formatSize(item.Size)  }}</Tag>
                  <Tag  mark :type="dlf(item.DownloadVolumeFactor).type">{{  dlf(item.DownloadVolumeFactor).text  }}</Tag>
                  <Tag  mark :type="ulf(item.UploadVolumeFactor).type">{{  ulf(item.UploadVolumeFactor).text  }}</Tag>
                </Space>
              </div>
            </template>
            <template #label>
              <p class="label-desc">{{  item.Description }}</p>
              <p class="label-time">{{  item.PublishDate.replace('T', ' ')  }}</p>
              <Space>
                <Tag :type="item.TrackerType==='public'?'default':'warning'">{{  item.Tracker  }}</Tag>
                <Tag plain type="primary">{{  item.CategoryDesc  }}</Tag>
                <Tag plain type="primary" >{{  item.Seeders  }} Seeders</Tag>
                <Tag plain type="primary" >{{  item.Peers  }} Leechers</Tag>
              </Space>
            </template>
          </Cell>
        </List>
      </PullRefresh>
      <ActionSheet v-model:show="opShow" :actions="actions" cancel-text="取消" close-on-click-action @select="onSelect" />
  
      <ActionSheet v-model:show="addShow" title="添加种子">
        <AddTorrent ref="addTorrent" @close="() => { addShow = false; onRefresh(); }" />
      </ActionSheet>
    </div>
  </template>
  
  <script name="jackett-mobile" setup>
  import { Sticky, Search, DropdownMenu, DropdownItem, Notify, PullRefresh, List, Cell, Switch, Space, Tag, ActionSheet, Button } from 'vant';
  import { reactive, ref, watchEffect, nextTick } from 'vue';
  
  import AddTorrent from '@/mobile/Torrent/Add.vue';

  import SearchApi from '@/api/SearchApi.js'

  import store from '@/store';

  import CommonUtil from '@/utils/CommonUtil.js'
  import TorrentUtil from '@/utils/TorrentUtil.js'
  
  const list = ref([]);
  const loading = ref(false);
  const finished = ref(false);
  const refreshing = ref(false);
  const error = ref(false);
  const errorText = ref('加载失败，请刷新重试');
  const searchForm = reactive({
    keyword: ''
  });

  const siteOptions = store.state.siteOptions;

  // 筛选
  const filter = reactive({
    indexer: '',
    trackerType: '',
    onlyFree: false
  });
  const filterList = ref([]);
  const indexerOptions = ref([{
    text: '全部',
    value: ''
  }]);
  const trackerTypeOptions = [
    {
      text: '类型',
      value: ''
    },
    {
      text: 'Public',
      value: 'public'
    },
    {
      text: 'Private',
      value: 'private'
    }
  ]
  const dItem = ref(null);
  
  let allList = [];
  const indexers = ref([]);
  const pagination = {
    current: 1,
    pageSize: 20,
  };
  const onLoad = async () => {
    if (allList.length == 0) {
        const response = await SearchApi.jackett(searchForm)
        if (response.data.code === 1) {
          allList = response.data.data.Results;
          indexers.value = response.data.data.Indexers;

          if (indexers.value.length > 0) {
            indexerOptions.value = [
            {
              text: '全部',
              value: ''
            },
            ...indexers.value.map(item => {
              return {
                text: `${item.Name}(${item.Results})`,
                value: item.ID,
                disabled: item.Results === 0
              }
            })
            ]
          }
          filterList.value = allList
          pagination.current = 1;
          list.value = [];
        } else {
          error.value = true;
          errorText.value = response.data.message;
        }
    }
    loading.value = false;
    if (!error.value) {

      list.value = list.value.concat(filterList.value.slice(pagination.current * pagination.pageSize - pagination.pageSize, pagination.current * pagination.pageSize));

      pagination.current++;

      if (list.value.length >= allList.length) {
          finished.value = true;
      }
    }    
  };

  const onFilter = () => {
    filterList.value = allList.filter(item => {
      if (filter.onlyFree && item.DownloadVolumeFactor !==0 ) return false;
      if (filter.indexer && item.TrackerId !== filter.indexer) return false;
      if (filter.trackerType && item.TrackerType !== filter.trackerType) return false;

      return true;
    })
    pagination.current = 1;
    list.value = [];
    onLoad()
  }
  
  const onRefresh = () => {
  
    if (!searchForm.keyword) {
      Notify({ type: 'warning', message: '请输入搜索关键词' });
      return;
    }
  
    refreshing.value = false;
  
    // 清空列表数据
    filter.category = '';
    allList = [];
    list.value = [];
    finished.value = false;

    error.value = false;
    errorText.value = '';
    // 重新加载数据
    // 将 loading 设置为 true，表示处于加载状态
    loading.value = true;
  
    onLoad();
  };
  
  //
  const addTorrent = ref(null);
  const addShow = ref(false);
  let toAddRow = undefined;
  const opShow = ref(false);
  const actions = reactive([
    { name: '添加', disabled: false },
    { name: '跳转', color: 'green' },
  ]);
  const opShowFunc = (item) => {
    toAddRow = {
      id: '',
      name: item.Title,
      address: item.MagnetUri ? item.MagnetUri : item.Guid,
      categoryid: item.CategoryMap,
      link: item.Details,
      hash: item.InfoHash,
    };
    actions[0].disabled = item.isAdd;
    opShow.value = true;
  }
  const onSelect = (item, index) => {
    // 默认情况下点击选项时不会自动收起
    // console.log(index, item.name);
    if (index === 0) {
      toAddRow.address = TorrentUtil.estimateAddress(toAddRow.address, siteOptions);
      addShow.value = true;
      nextTick(() => {
        addTorrent.value.initModel(toAddRow);
      })
    } else if (index === 1) {
      window.open(toAddRow.link);
    }
  };

  const dlf = (DownloadVolumeFactor) => {
    const r = {
      type: '',
      text: '-',
    }
    if (!isNaN(DownloadVolumeFactor)) {
        if (DownloadVolumeFactor == 0) {
            // success
            r.type = 'success';
            r.text = 'Free';
        } else if (DownloadVolumeFactor < 1) {
            // primary
            r.type = 'primary';
            r.text = (DownloadVolumeFactor * 100).toFixed(0) + '%DL';
        } else if (DownloadVolumeFactor > 1) {
            // danger
            r.type = 'danger';
            r.text = (DownloadVolumeFactor * 100).toFixed(0) + '%DL';
        }
    }
    return r;
  }

  const ulf = (UploadVolumeFactor) => {
    let r = {
      type: '',
      text: '-',
    }
    if (!isNaN(UploadVolumeFactor)) {
        if (UploadVolumeFactor == 0) {
          // warning
          r.type = 'warning';
          r.text = 'NO UPLOAD';
        } else if (UploadVolumeFactor != 1) {
          // info
          r.type = 'info';
          r.text = (UploadVolumeFactor * 100).toFixed(0) + '%UL';
        }
    }
    return r;
  }
  


  watchEffect(() => {
  })
  // init functions
  
  </script>
  <style scoped>
  
  .row-title {}
  
  .label-time {
    /* margin: 0;
    padding: 0; */
  }
  .label-desc {
    /* border-bottom: 1px solid lightgray; */
  }
  
  .menu-btn {
    position: fixed;
    bottom: 20px;
    /* right: 20px; */
    width: 100%;
    text-align: right;
    padding-right: 20px;
  }
  </style>